package org.kth.dks.dks_marshal;

/**
 * <p>Title: DKS</p>
 * <p>Description: DKS Middleware</p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: KTH-IMIT</p>
 * @author Ali Ghodsi (aligh@kth.se)
 * @version 1.0
 */

import java.io.IOException;

import org.kth.dks.DKSObject;
import org.kth.dks.dks_comm.DKSRef;
import org.kth.dks.dks_node.LookupType;

public class LookupResponseMsg extends DKSMessage { // shouldnt be public!
  private static String NAME= "LOOKUPRESPONSE";
  private DKSRef targetRef;
  private LookupType type;
  private String msgId;
  private DKSObject payload=null;  // invariant: only used if type==LookupType.DATA

  public String getName() { return NAME; }
  public DKSRef getTargetRef() { return targetRef; }
  public LookupType getType() { return type; }
  public String getMsgId() { return msgId; }
  public DKSObject getPayload() { return payload; }

  public LookupResponseMsg() {

  }

  public LookupResponseMsg(DKSRef target, LookupType type, String msgId) {

    this.targetRef=target;
    this.type=type;
    this.msgId=msgId;
  }

  /* this version of the constructor has a DKSObject payload
      invariant: should only be used if type==LookupType.DATA, else above constructor should be used
   */
  public LookupResponseMsg(DKSRef target, LookupType type, DKSObject payload, String msgId) {

    this.targetRef=target;
    this.type=type;
    this.msgId=msgId;
    this.payload=payload;
  }

  public void marshal() throws IOException {
    marshaler.addDKSRef( targetRef, "target" );
    marshaler.addString( type.toString(), "type" );

    marshaler.addBool(payload == null ? false : true , "anypayload");
    if (payload != null) {
      marshaler.addDKSObject(payload, "payload");
    }

    marshaler.addBool(msgId == null ? false : true , "anyinsertid");
    if (msgId != null) {
      marshaler.addString(msgId, "insertid");
    }

  }

  public void unmarshal() throws IOException  {
    targetRef   = marshaler.remDKSRef("target");
    type        = LookupType.valueOf( marshaler.remString("type") );

    final boolean anyLoad = marshaler.remBool("anypayload");
    if (anyLoad) {
      payload = marshaler.remDKSObject("payload");
    }

    final boolean anyId = marshaler.remBool("anyinsertid");
    if (anyId) {
      msgId = marshaler.remString("insertid");
    }
  }
}
